import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'index.dart';

class SharedPreferencesPage extends GetView<SharedPreferencesController> {
  const SharedPreferencesPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 20),
          
          // 页面头部
          _buildHeader(),
          
          const SizedBox(height: 30),
          
          // 统计信息区域
          _buildStatisticsSection(),
          
          const SizedBox(height: 20),
          
          // 应用设置区域
          _buildAppSettingsSection(),
          
          const SizedBox(height: 20),
          
          // 搜索功能区域
          _buildSearchSection(),
          
          const SizedBox(height: 20),
          
          // 操作按钮区域
          _buildActionButtons(),
          
          const SizedBox(height: 20),
          
          // 存储项列表区域
          _buildStorageItemsList(),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  // 构建页面头部
  Widget _buildHeader() {
    return Column(
      children: [
        Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.purple.shade400, Colors.purple.shade600],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.purple.withOpacity(0.3),
                blurRadius: 15,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: const Icon(
            Icons.storage,
            color: Colors.white,
            size: 40,
          ),
        ),
        const SizedBox(height: 20),
        Text(
          controller.pageTitle,
          style: const TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '查看和管理应用本地存储数据',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey.shade600,
          ),
        ),
      ],
    );
  }

  // 构建统计信息区域
  Widget _buildStatisticsSection() {
    if (!controller.isInitialized.value) {
      return const SizedBox.shrink();
    }
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue.shade50, Colors.blue.shade100],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Colors.blue.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.analytics_outlined,
                color: Colors.blue.shade600,
                size: 24,
              ),
              const SizedBox(width: 12),
              const Text(
                '存储统计',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          Row(
            children: [
              Expanded(
                child: _buildStatCard(
                  '存储项总数',
                  '${controller.totalStorageCount.value}',
                  Icons.storage_outlined,
                  Colors.green.shade600,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatCard(
                  '类型统计',
                  '${controller.getStorageStats().length}',
                  Icons.category_outlined,
                  Colors.orange.shade600,
                ),
              ),
            ],
          ),
          
          if (controller.lastRefreshTime.value != null) ...[
            const SizedBox(height: 12),
            Text(
              '最后更新: ${controller.lastRefreshTime.value}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey.shade600,
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 构建统计卡片
  Widget _buildStatCard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: color.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 20),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            title,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade600,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  // 构建应用设置区域
  Widget _buildAppSettingsSection() {
    if (controller.appSettings.isEmpty) {
      return const SizedBox.shrink();
    }
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.green.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.green.shade200,
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.settings_applications,
                color: Colors.green.shade600,
                size: 20,
              ),
              const SizedBox(width: 8),
              Text(
                '应用级设置',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.green.shade800,
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 12),
          
          ...controller.appSettings.entries.map((entry) => 
            _buildAppSettingItem(entry.key, entry.value.toString())
          ).toList(),
        ],
      ),
    );
  }

  // 构建应用设置项
  Widget _buildAppSettingItem(String key, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Text(
              key,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Colors.black87,
              ),
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6),
                border: Border.all(
                  color: Colors.green.shade200,
                  width: 1,
                ),
              ),
              child: Text(
                value,
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.green.shade700,
                  fontFamily: 'monospace',
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建搜索功能区域
  Widget _buildSearchSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.grey.shade300,
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.search,
                color: Colors.grey.shade600,
                size: 20,
              ),
              const SizedBox(width: 8),
              Text(
                '搜索存储项',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.shade800,
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 12),
          
          TextField(
            controller: controller.searchController,
            onChanged: controller.searchStorageItems,
            decoration: InputDecoration(
              hintText: '输入键名或值进行搜索...',
              hintStyle: TextStyle(color: Colors.grey.shade500),
              prefixIcon: Icon(Icons.search, color: Colors.grey.shade500),
              suffixIcon: controller.searchKeyword.isNotEmpty
                  ? IconButton(
                      onPressed: () {
                        controller.searchController.clear();
                        controller.searchStorageItems('');
                      },
                      icon: Icon(Icons.clear, color: Colors.grey.shade500),
                    )
                  : null,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide(color: Colors.grey.shade300),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide(color: Colors.blue.shade400),
              ),
              contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            ),
          ),
          
          if (controller.searchResults.isNotEmpty) ...[
            const SizedBox(height: 8),
            Text(
              '找到 ${controller.searchResults.length} 个结果',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey.shade600,
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 构建操作按钮区域
  Widget _buildActionButtons() {
    return Row(
      children: [
        // 刷新按钮
        Expanded(
          child: SizedBox(
            height: 48,
            child: ElevatedButton.icon(
              onPressed: controller.isLoading.value ? null : controller.refreshStorageData,
              icon: controller.isLoading.value
                  ? SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : const Icon(Icons.refresh, size: 20),
              label: Text(
                controller.isLoading.value ? '加载中...' : '刷新数据',
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue.shade600,
                foregroundColor: Colors.white,
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
          ),
        ),
        
        const SizedBox(width: 12),
        
        // 清空按钮
        Expanded(
          child: SizedBox(
            height: 48,
            child: ElevatedButton.icon(
              onPressed: controller.storageItems.isNotEmpty && !controller.isLoading.value
                  ? () => _showClearConfirmDialog()
                  : null,
              icon: const Icon(Icons.delete_sweep, size: 20),
              label: const Text(
                '清空数据',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red.shade600,
                foregroundColor: Colors.white,
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建存储项列表
  Widget _buildStorageItemsList() {
    if (controller.hasError.value) {
      return _buildErrorWidget();
    }
    
    if (controller.isLoading.value) {
      return _buildLoadingWidget();
    }
    
    if (!controller.isInitialized.value) {
      return const SizedBox.shrink();
    }
    
    final itemsToShow = controller.searchKeyword.isNotEmpty 
        ? controller.searchResults 
        : controller.storageItems;
    
    if (itemsToShow.isEmpty) {
      return _buildEmptyWidget();
    }
    
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.grey.shade300,
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.list_alt,
                  color: Colors.grey.shade600,
                  size: 20,
                ),
                const SizedBox(width: 8),
                Text(
                  controller.searchKeyword.isNotEmpty ? '搜索结果' : '所有存储项',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey.shade800,
                  ),
                ),
                const Spacer(),
                Text(
                  '${itemsToShow.length} 项',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
          
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: itemsToShow.length,
            separatorBuilder: (context, index) => Divider(
              height: 0.5,
              thickness: 0.5,
              color: Colors.grey.shade300,
              indent: 16,
              endIndent: 16,
            ),
            itemBuilder: (context, index) {
              final item = itemsToShow[index];
              return _buildStorageItemTile(item);
            },
          ),
        ],
      ),
    );
  }

  // 构建存储项磁贴 - 紧凑布局
  Widget _buildStorageItemTile(StorageItem item) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () => _showStorageItemDetail(item),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 左侧：类型标签
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: _getTypeColor(item.type).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  item.type,
                  style: TextStyle(
                    fontSize: 9,
                    fontWeight: FontWeight.w500,
                    color: _getTypeColor(item.type),
                  ),
                ),
              ),
              
              const SizedBox(width: 8),
              
              // 中间：键名和值
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 键名行
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            item.key,
                            style: const TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        // 应用设置标签
                        if (item.isAppSetting) ...[
                          const SizedBox(width: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                            decoration: BoxDecoration(
                              color: Colors.green.shade100,
                              borderRadius: BorderRadius.circular(3),
                            ),
                            child: Text(
                              '应用',
                              style: TextStyle(
                                fontSize: 8,
                                fontWeight: FontWeight.w500,
                                color: Colors.green.shade700,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    
                    const SizedBox(height: 2),
                    
                    // 值
                    Text(
                      item.value,
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.grey.shade600,
                        fontFamily: 'monospace',
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              
              const SizedBox(width: 8),
              
              // 右侧：操作按钮
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 详情按钮
                  IconButton(
                    onPressed: () => _showStorageItemDetail(item),
                    icon: Icon(
                      Icons.info_outline,
                      size: 18,
                      color: Colors.blue.shade400,
                    ),
                    tooltip: '查看详情',
                    padding: const EdgeInsets.all(4),
                    constraints: const BoxConstraints(
                      minWidth: 32,
                      minHeight: 32,
                    ),
                  ),
                  // 删除按钮
                  IconButton(
                    onPressed: () => _showDeleteConfirmDialog(item.key),
                    icon: Icon(
                      Icons.delete_outline,
                      size: 18,
                      color: Colors.red.shade400,
                    ),
                    tooltip: '删除此项',
                    padding: const EdgeInsets.all(4),
                    constraints: const BoxConstraints(
                      minWidth: 32,
                      minHeight: 32,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建加载中组件
  Widget _buildLoadingWidget() {
    return Container(
      padding: const EdgeInsets.all(40),
      child: const Column(
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text(
            '正在加载存储数据...',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  // 构建错误组件
  Widget _buildErrorWidget() {
    return Container(
      padding: const EdgeInsets.all(40),
      child: Column(
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.red.shade600,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            controller.errorMessage,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey.shade600,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            onPressed: controller.refreshStorageData,
            icon: const Icon(Icons.refresh),
            label: const Text('重试'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue.shade600,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  // 构建空状态组件
  Widget _buildEmptyWidget() {
    final isSearching = controller.searchKeyword.isNotEmpty;
    
    return Container(
      padding: const EdgeInsets.all(40),
      child: Column(
        children: [
          Icon(
            isSearching ? Icons.search_off : Icons.storage_outlined,
            size: 64,
            color: Colors.grey.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            isSearching ? '未找到匹配项' : '暂无存储数据',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade600,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            isSearching 
                ? '尝试使用其他关键词搜索'
                : '当前没有任何本地存储数据',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey.shade500,
            ),
          ),
        ],
      ),
    );
  }

  // 辅助方法：获取类型颜色
  Color _getTypeColor(String type) {
    switch (type) {
      case 'String':
        return Colors.blue.shade600;
      case 'Bool':
        return Colors.green.shade600;
      case 'Int':
        return Colors.orange.shade600;
      case 'Double':
        return Colors.deepOrange.shade600;
      case 'Object':
        return Colors.purple.shade600;
      case 'StringList':
        return Colors.teal.shade600;
      default:
        return Colors.grey.shade600;
    }
  }

  // 显示删除确认对话框
  void _showDeleteConfirmDialog(String key) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除存储项 "$key" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.deleteStorageItem(key);
            },
            child: Text(
              '删除',
              style: TextStyle(color: Colors.red.shade600),
            ),
          ),
        ],
      ),
    );
  }

  // 显示清空确认对话框
  void _showClearConfirmDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认清空'),
        content: const Text('确定要清空所有存储数据吗？此操作不可撤销，将删除所有应用数据。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.clearAllStorageData();
            },
            child: Text(
              '清空',
              style: TextStyle(color: Colors.red.shade600),
            ),
          ),
        ],
      ),
    );
  }

  // 显示存储项详情对话框
  void _showStorageItemDetail(StorageItem item) {
    final detail = controller.getStorageItemDetail(item.key);
    final RxBool showFormatted = (detail['isJsonFormatted'] == true).obs;
    
    Get.dialog(
      AlertDialog(
        title: Row(
          children: [
            Icon(
              Icons.info_outline,
              color: _getTypeColor(item.type),
              size: 24,
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                '存储项详情',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          constraints: const BoxConstraints(maxHeight: 650),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 基本信息
                _buildDetailItem('键名', detail['key']),
                _buildDetailItem('数据类型', detail['type']),
                _buildDetailItem('是否为应用设置', detail['isAppSetting'] ? '是' : '否'),
                _buildDetailItem('键是否存在', detail['keyExists'] ? '是' : '否'),
                _buildDetailItem('值长度', '${detail['valueLength']} 字符'),
                
                const SizedBox(height: 12),
                
                // 完整值
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade50,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.grey.shade300),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '完整值',
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey.shade700,
                            ),
                          ),
                          if (detail['isJsonFormatted'] == true) ...[
                            const SizedBox(width: 8),
                            Obx(() => Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: showFormatted.value ? Colors.green.shade100 : Colors.orange.shade100,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                showFormatted.value ? 'JSON格式化' : '原始值',
                                style: TextStyle(
                                  fontSize: 9,
                                  fontWeight: FontWeight.w500,
                                  color: showFormatted.value ? Colors.green.shade700 : Colors.orange.shade700,
                                ),
                              ),
                            )),
                            const SizedBox(width: 8),
                            InkWell(
                              onTap: () => showFormatted.toggle(),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: BoxDecoration(
                                  color: Colors.blue.shade100,
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: Icon(
                                  Icons.swap_horiz,
                                  size: 14,
                                  color: Colors.blue.shade600,
                                ),
                              ),
                            ),
                            const SizedBox(width: 8),
                            InkWell(
                              onTap: () => _copyToClipboard(
                                showFormatted.value 
                                  ? (detail['formattedValue'] ?? '')
                                  : (detail['displayValue'] ?? '')
                              ),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade200,
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: Icon(
                                  Icons.copy,
                                  size: 14,
                                  color: Colors.grey.shade600,
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                      const SizedBox(height: 6),
                      Container(
                        width: double.infinity,
                        constraints: const BoxConstraints(maxHeight: 400),
                        child: SingleChildScrollView(
                          child: detail['isJsonFormatted'] == true 
                            ? Obx(() => SelectableText(
                                showFormatted.value 
                                  ? (detail['formattedValue'] ?? 'null')
                                  : (detail['displayValue'] ?? 'null'),
                                style: TextStyle(
                                  fontSize: showFormatted.value ? 10 : 11,
                                  color: Colors.black87,
                                  fontFamily: 'monospace',
                                  height: showFormatted.value ? 1.3 : 1.1,
                                ),
                              ))
                            : SelectableText(
                                detail['displayValue'] ?? 'null',
                                style: const TextStyle(
                                  fontSize: 11,
                                  color: Colors.black87,
                                  fontFamily: 'monospace',
                                  height: 1.1,
                                ),
                              ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              _showDeleteConfirmDialog(item.key);
            },
            child: Text(
              '删除',
              style: TextStyle(color: Colors.red.shade600),
            ),
          ),
        ],
      ),
    );
  }

  // 构建详情项 - 紧凑单行布局
  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 70,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w500,
                color: Colors.grey.shade600,
              ),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 11,
                color: Colors.black87,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 显示统计信息对话框
  void _showStatsDialog() {
    final stats = controller.getStorageStats();
    
    Get.dialog(
      AlertDialog(
        title: const Text('存储类型统计'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('总存储项：${controller.totalStorageCount.value}'),
            const SizedBox(height: 12),
            ...stats.entries.map((entry) => Padding(
              padding: const EdgeInsets.symmetric(vertical: 2),
              child: Row(
                children: [
                  Container(
                    width: 12,
                    height: 12,
                    decoration: BoxDecoration(
                      color: _getTypeColor(entry.key),
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text('${entry.key}: ${entry.value}'),
                ],
              ),
            )).toList(),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 复制文本到剪贴板
  void _copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
    Get.snackbar(
      '复制成功',
      '内容已复制到剪贴板',
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 2),
      backgroundColor: Colors.green.shade100,
      colorText: Colors.green.shade800,
      margin: const EdgeInsets.all(16),
      borderRadius: 8,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SharedPreferencesController>(
      init: SharedPreferencesController(),
      id: "shared_preferences",
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(Icons.arrow_back_ios, color: Colors.black87, size: 20),
              onPressed: () => Get.back(),
            ),
            title: Text(
              controller.pageTitle,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
            backgroundColor: Colors.white,
            elevation: 0,
            scrolledUnderElevation: 0,
            surfaceTintColor: Colors.transparent,
            foregroundColor: Colors.black87,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark,
            ),
            actions: [
              // 统计信息图标
              IconButton(
                onPressed: () => _showStatsDialog(),
                icon: const Icon(Icons.pie_chart_outline),
                tooltip: '存储统计',
              ),
            ],
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
